#encoding:utf-8
'''
Created on 2015年8月19日

@author: liuxue
'''
import hashlib
import json
import base64
import time
def multipart_upload(filename, file_size, file_md5, secret, file_blocks=1, expiration=86400):
    '''
    分块上传
    @param filename: 文件名称
    @file_size: 文件大小
    @file_md5: 文件md5
    @secret: 上传密钥
    @file_blocks:分块数量
    @expiration:超时时间
    '''
    expired_at = int(expiration+time.time())
    policy = {"path":"/upload/"+filename,"expiration":expired_at,"file_blocks":file_blocks,"file_size":file_size,"file_hash":file_md5}
    sorted_keys = sorted(policy.keys())
    
    tmp = ''
    for key in sorted_keys:
        tmp = tmp + ('%s%s'%(key, policy[key]))

    tmp = tmp + secret
    md5 = hashlib.md5()
    md5.update(tmp.encode())
    md5sum = md5.hexdigest()
    
    return base64.encodestring(json.dumps(policy).encode()).decode().replace('\n', ''), md5sum, expired_at
    
    
if __name__ == '__main__':
    bucket = 'demonstration'
    secret = '1+JY2ZqD5UVfw6hQ8EesYQO50Wo='
    req = 'http://m0.api.upyun.com/%s/'%bucket
    
    filename = 'test1439994217.jpg'
    file_size = 30485
    file_md5 = '9f2f88c336798f6f376dad7dbfd3f38b'
    
    policy, sign, expired_at = multipart_upload(filename, file_size, file_md5, secret)

    from urllib.request import urlopen, Request
    from urllib.parse import urlencode
    data = {
            'policy':policy,
            'signature':sign
            }
    print(urlencode(data).encode())
    with urlopen(Request(req, headers={'Content-Type' : 'application/x-www-form-urlencoded'},method='POST', data=urlencode(data).encode()), 
                 ) as f:
        print(f.read())